<template>
	<view class="t_top">
		<image src="/static/dw.png" mode=""></image>
		<view v-if="address" class="flex_r" @click="$pageGo('/pages/user/address?type=1')">
			<view class="flex_jc_sb">
				<view class="text">
					{{address.userName}} {{address.userPhone}}
				</view>
				<uni-icons type="right"></uni-icons>
			</view>
			<view class="texts">
				<!-- {{address.province}}{{address.city}}{{address.county}} -->{{address.address}}
			</view>
		</view>
		<view v-else class="text1 " @click="$pageGo('/pages/user/address?type=1')">
			请选择收货地址
		</view>
		<image class="xx" src="/static/xx.png" mode=""></image>
	</view>

	<view class="block_1">
		<view class="title flex_jc_sb">
			<view class="title_l">
				配送时间
			</view>
			<view class="title_r">
				预计 <text>{{time}}</text> 前送达
			</view>
		</view>
		<view class="item_2 flex_jc_sb">
			<view class="images flex">
				<image v-for="(item,index) in params.productList.slice(0,3)" :key="index" :src="item.product.icon"
					mode="aspectFit"></image>
			</view>
			<view class="righttext flex" @click="gocardetail()">
				共{{params.productList.length}}种 <uni-icons color="#D1D1D6" size="16" type="right"></uni-icons>
			</view>
		</view>
	</view>
	<view class="info">
		<view class="title">
			商品信息
		</view>
		<view class="item flex_jc_sb">
			<view class="i_l">
				商品件数
			</view>
			<view class="i_r">
				{{allCount}}
			</view>
		</view>
		<view class="item flex_jc_sb">
			<view class="i_l">
				商品金额
			</view>
			<view class="i_r">
				￥{{Price}}
			</view>
		</view>
		<view class="item flex_jc_sb">
			<view class="i_l">
				配送费
			</view>
			<view class="i_r flex">
				<text>满{{amount.deliveryAmountRequire}}免配送费</text>
				<text :class="isshow?'prive1':'prive'"> ￥{{amount.deliveryAmount}}</text>
			</view>
		</view>
		<view class="hj">
			共{{allCount}}件，合计: <text>￥</text> <text class="t1">{{allPrice}}</text>
		</view>
	</view>


	<view class="play">
		<view class="title">
			支付方式
		</view>
		<view class="item flex_jc_sb" @click="changeType('微信支付')">
			<view class="i_l flex">
				<image src="/static/wf.png" mode=""></image>
				微信支付
			</view>
			<view class="i_r">
				<image v-if="params.orderType == '微信支付'" src="/static/radioact.png" mode=""></image>
				<image v-else src="/static/radio.png" mode=""></image>
			</view>
		</view>
		<view class="item flex_jc_sb" @click="changeType('月结')" v-if="userInfo.level =='金牌'">
			<view class="i_l flex">
				<image src="/static/yf.png" mode=""></image>
				月结
			</view>
			<view class="i_r flex">
				<text>可用额度:￥{{userInfo.debtLimit - userInfo.debtAmount}}</text>
				<image v-if="params.orderType == '月结'" src="/static/radioact.png" mode=""></image>
				<image v-else src="/static/radio.png" mode=""></image>
			</view>
		</view>
	</view>
	<view class="" style="height: 266rpx;">

	</view>
	<view class="footer">
		<view class="cont flex_jc_sb">
			<view class="hj">
				合计: <text>￥</text> <text class="t1">{{allPrice}}</text>
			</view>
			<view class="btn" @click="handleConfirm">
				立即支付
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		useStore
	} from 'vuex';
	import {
		reactive,
		ref,
		computed
	} from 'vue';
	import {
		chattering
	} from '@/common/cont.js'
	import {
		addressDefault,
		deliveryAmount,
		getUserInfo,
		createOrder,
		getShopCar
	} from '@/common/http.api.js';
	const store = useStore();
	const time = computed(() => {
		// let timenum = tt * 1000
		let t = new Date().getTime()
		const oneDay = 1000*60*60*24;
		var date = new Date(t)
		const nowhours =date.getHours()
		console.log(nowhours);
		if(nowhours>=17){
			// 大于17 隔日16点送达
			console.log('隔日');
		   date = new Date(t+oneDay*2)
		}
		if(nowhours<17){
			// 小于17 次日16点送达
			console.log('、次日');
			date = new Date(t+oneDay)
		}
		// 补零函数
		const padZero = num => num.toString().padStart(2, '0');
		// 提取日期各部分
		const year = date.getFullYear();
		const month = padZero(date.getMonth() + 1); // 月份从0开始需+1
		const day = padZero(date.getDate());
		// 周几映射（0: 周日，1: 周一，...）
		const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
		const weekday = weekdays[date.getDay()];
		return `${month}月${day}日(周${weekday}) 16:00  `;
	})
	const Price = computed(() => {
		let price = 0;
		params.productList.forEach(its => {
			price += its.product.price * its.productCount
		})
		return price.toFixed(2)
	})
	const allPrice = computed(() => {
		let price = 0;
		params.productList.forEach(its => {
			price += its.product.price * its.productCount
		})
		if (price < amount.value.deliveryAmountRequire) {
			isshow.value = true
			price += amount.value.deliveryAmount
			return price.toFixed(2)
		} else {
			isshow.value = false
			// price -= amount.value.deliveryAmount
			return price.toFixed(2)
		}
	})
	const allCount = computed(() => {
		let total = 0;
		params.productList.forEach(its => {
			total += its.productCount
		})
		return total
	})
	const params = reactive({
		"orderType": "",
		"deliveryName": "",
		"deliveryPhone": "",
		"deliveryProvince": "",
		"deliveryCity": "",
		"deliveryCounty": "",
		"deliveryAddress": "",
		"productList": []
	})
	const address = ref({
		userName: ''
	})
	const amount = ref({})
	const isshow = ref(false)
	const userInfo = ref({})
	onLoad(() => {
		console.log(new Date().getTime());
		getUserInfo({}).then(res => {
			userInfo.value = res.data
		})
		deliveryAmount({}).then(res => {
			amount.value = res.data
		})
		params.productList = uni.getStorageSync('shopList')
		//默认地址
		addressDefault({}).then(res => {
			address.value = res.data
		})
	})
	onShow(() => {
		uni.$on('address', function(data) {
			address.value = data
		})
	})


	function changeType(orderType) {
		params.orderType = orderType
	}

	function gocardetail() {
		let list = params.productList.map(item => {
			return {
				productCount: item.productCount,
				productIcon: item.product.icon,
				productName: item.product.name,
				productPrice: item.product.price,
				productUnit: item.product.unit,
			}
		})
		uni.setStorageSync('Infolist', list)
		uni.navigateTo({
			url: '/pages/shopcart/cardetail'
		})
	}

	function handleConfirm() {
		if (address.value) {
			params.deliveryName = address.value.userName
			params.deliveryPhone = address.value.userPhone
			params.deliveryProvince = address.value.province
			params.deliveryCity = address.value.city
			params.deliveryCounty = address.value.county
			params.deliveryAddress = address.value.address
		}
		if (params.deliveryName == '') {
			uni.showToast({
				title: '请选择配送地址',
				icon: 'none'
			})
			return
		}
		if (params.orderType == '') {
			uni.showToast({
				title: '请选择支付方式',
				icon: 'none'
			})
			return
		}
		uni.showLoading({
			title: '支付中...'
		})
		chattering(() => {
			createOrder(params).then(res => {
				if (res.code == 200) {
					// 微信支付
					if (res.data.pay_status == '0') {
						uni.hideLoading()
						uni.requestPayment({
							"provider": "wxpay", //固定值为"wxpay"
							appid: res.data.pay_info.appId, // 应用ID（AppID）
							package: res.data.pay_info.packageVal, // 固定值
							nonceStr: res.data.pay_info.nonceStr, // 随机字符串
							timeStamp: res.data.pay_info.timestamp, // 时间戳（单位：秒）
							signType: res.data.pay_info.signType, // 签名，这里用的 MD5 签名
							paySign: res.data.pay_info.paySign,
							success: function(res) {
								console.log(res);
								uni.showToast({
									icon: 'none',
									title: '支付成功'
								})
								setTimeout(() => {
									uni.removeStorageSync('shopList')
									uni.redirectTo({
										url: `/pages/shopcart/orderyes?price=${allPrice.value}`
									})
								}, 100)
							},
							fail: function(err) {
								console.log(err);
								uni.showToast({
									icon: 'none',
									title: '支付取消'
								})
								setTimeout(() => {
									getShopCar({}).then(res => {
										if (res.code == 200) {
											let total = res.data.reduce((sum,
												e) => sum + Number(e
												.productCount || 0), 0)
											store.commit('setShopNum', total)
										}
									})
									uni.removeStorageSync('shopList')
									uni.reLaunch({
										url: '/pages/user/user'
									})
								}, 100)
							}
						});

					}
					// 月结
					if (res.data.pay_status == '1') {
						uni.hideLoading()
						uni.removeStorageSync('shopList')
						uni.redirectTo({
							url: `/pages/shopcart/orderyes?price=${allPrice.value}`
						})
					}
				}
			})
		})

	}
</script>

<style lang="scss">
	page {
		background: #F8F8F8;
	}

	.t_top {
		width: 710rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: 20rpx auto;
		padding: 36rpx 20rpx;
		box-sizing: border-box;
		display: flex;
		position: relative;

		.text1 {
			flex: 1;
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 36rpx;
			color: #000000;
			line-height: 40rpx;
			margin-left: 15rpx;
		}

		.xx {
			width: 660rpx;
			height: 5rpx;
			position: absolute;
			bottom: 0%;
		}

		image {
			width: 40rpx;
			height: 40rpx;
		}

		.flex_r {
			flex: 1;
			margin-left: 15rpx;

			.text {
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #000000;
			}

			.texts {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #000000;
				margin-top: 15rpx;
			}
		}
	}

	.block_1 {
		width: 710rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: 20rpx auto;
		padding: 30rpx 20rpx;
		box-sizing: border-box;

		.title {
			padding-bottom: 30rpx;
			border-bottom: 1px solid #DADADA;

			.title_l {
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 30rpx;
				color: #000000;
			}

			.title_r {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #000000;

				text {
					color: #FF7700;
				}
			}
		}

		.item_2 {
			margin-top: 20rpx;

			.images {
				image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 12rpx;
					border: 1px solid #DADADA;
					margin-right: 20rpx;
				}
			}

			.righttext {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #979797;
			}
		}
	}


	.info {
		width: 710rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: 20rpx auto;
		padding: 30rpx 20rpx;
		box-sizing: border-box;

		.title {
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 30rpx;
			color: #000000;
		}

		.item {
			margin-top: 30rpx;

			.i_l {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #979797;
			}

			.i_r {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #000000;

				text {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 22rpx;
					color: #FF0000;
				}

				.prive {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #979797;
					line-height: 33rpx;
					text-align: right;
					font-style: normal;
					margin-left: 10rpx;
					text-decoration-line: line-through;
				}

				.prive1 {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #000000;
				}
			}
		}

		.hj {
			text-align: right;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #000000;
			margin-top: 30rpx;
			padding-top: 20rpx;
			border-top: 1px solid #DADADA;

			.t1 {
				font-size: 40rpx;
			}

			text {
				color: #FF0000;
			}
		}
	}

	.play {
		width: 710rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: 20rpx auto;
		padding: 30rpx 20rpx;
		box-sizing: border-box;

		.title {
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 30rpx;
			color: #000000;
		}

		.item {
			padding-bottom: 30rpx;
			border-bottom: 1px solid #DADADA;
			margin-top: 30rpx;
		}

		.item:last-child {
			border: none;
			padding-bottom: 0rpx;
		}

		.i_l {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #000000;

			image {
				width: 52rpx;
				height: 52rpx;
				margin-right: 20rpx;
			}
		}

		.i_r {
			text {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 22rpx;
				color: #979797;
				margin-right: 20rpx;
			}

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.footer {
		width: 750rpx;
		height: 120rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 1rpx 10rpx 0rpx rgba(0, 0, 0, 0.2);
		position: fixed;
		bottom: 0%;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.cont {
			padding: 30rpx 30rpx 10rpx 40rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			height: 120rpx;
			color: #000000;

			.hj {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #000000;

				.t1 {
					font-size: 40rpx;
				}

				text {
					color: #FF0000;
				}
			}

			.btn {
				width: 420rpx;
				height: 80rpx;
				background: #FF7700;
				border-radius: 40rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 80rpx;
				text-align: center;
			}
		}
	}
</style>